package cn.doitedu.api;


import beans.OrderBean;
import com.alibaba.fastjson.JSONObject;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author: 深似海
 * @Site: <a href="www.51doit.com">多易教育</a>
 * @QQ: 657270652
 * @Date: 2024/2/27
 * @Desc: 学大数据，上多易教育
 * 有如下订单数据:
 * 订单id,商品id,品类id,金额,订单创建时间
 * o1,p1,category_01,1800,1709027697000
 * o1,p2,category_01,1600,1709027697000
 * o1,p3,category_02,1600,1709027697000
 * o2,p3,category_02,1600,1709027697000
 * o3,p4,category_03,1200,1709027697000
 * <p>
 * 统计:
 * 1. 最近 5分钟的成交总额，要求每 1分钟输出一次结果；
 * 2. 每 5分钟，各品类各商品的下单数;
 * 3. 每 5分钟，成交金额最高的前3种商品及其成交金额
 **/
public class _27_Exercise_Window_2 {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        env.enableCheckpointing(5000);
        env.getCheckpointConfig().setCheckpointStorage("file:///d:/ckpt");

        DataStreamSource<String> stream = env.socketTextStream("localhost", 8899);

        DataStream<OrderBean> mapped = stream.map(s -> {
            String[] split = s.split(",");
            return new OrderBean(split[0], split[1], split[2], Double.parseDouble(split[3]), Long.parseLong(split[4]));
        }).assignTimestampsAndWatermarks(
                WatermarkStrategy
                        .<OrderBean>forBoundedOutOfOrderness(Duration.ZERO)
                        .withTimestampAssigner(new SerializableTimestampAssigner<OrderBean>() {
                            @Override
                            public long extractTimestamp(OrderBean element, long recordTimestamp) {
                                return element.getCreate_time();
                            }
                        }));


        mapped.keyBy(bean -> {
                    return Tuple2.of(bean.getCategoryId(),bean.getProductId());
                })
                .window(TumblingEventTimeWindows.of(Time.minutes(5)))
                .process(new ProcessWindowFunction<OrderBean, String, Tuple2<String, String>, TimeWindow>() {
                    @Override
                    public void process(Tuple2<String, String> key, ProcessWindowFunction<OrderBean, String, Tuple2<String, String>, TimeWindow>.Context context, Iterable<OrderBean> elements, Collector<String> out) throws Exception {

                        // 各品类各商品的下单数
                        int count = 0;
                        for (OrderBean element : elements) {
                            count++;
                        }

                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("window_start",context.window().getStart());
                        jsonObject.put("window_end",context.window().getEnd());
                        jsonObject.put("category_id",key.f0);
                        jsonObject.put("product_id",key.f1);
                        jsonObject.put("order_count",count);

                        out.collect(jsonObject.toJSONString());

                    }
                }).print();

        env.execute();

    }


}
